<template>
	<view class="d-kuan d-juzhong">

				<uv-overlay :show="zanzhu_data_show" @tap="zanzhu_data_add_close" zIndex="998" opacity="0.5">
			    <view class="warp_zanzhu">
			    	<view class="rect_zanzhu" @tap.stop.prevent>
			    		<uv-cell-group>
              
			    			<uv-cell icon="clock" title="赞助金"></uv-cell>
			    		</uv-cell-group>
              <uv-input placeholder="标题" border="surround" v-model="zanzhu_data_add.title" :value="zanzhu_data_add.title">
                  <template v-slot:prefix>
                  	<uv-text
                  		text="标题"
                  		margin="0 10px 0 0"
                  		type="tips"
                  	></uv-text>
                  </template>
              </uv-input>
              <view class="d-shang-10 d-kuan ">
                <view class="d-neikuang-10 ">
                  <view class="d-kuan d-wenzi-14 d-xia-10">
                    <view class="d-zuo"></view><view class="d-you" @click="zanzhu_tianjia">+添加</view>
                  </view>
                  <view class="d-clear d-shang-10"></view>
                  <!-- 动态渲染赞助金组 -->
                  <view class="d-kuan " id="d-gundong">
                    <view 
                      v-for="(item, index) in zanzhu_data_add.zanzhu" 
                      :key="index"
                      class="d-kuan d-yuanjiao-10 mb-10" 
                      :id="'chuangyeji_id_' + index" 
                      style="background-color: #f5f5f5; margin-bottom: 10px;"
                    >
                      <view class="d-neikuang-10">
                        <view class="d-kuan d-wenzi-14">
                          <view class="d-zuo">{{'第' + (index + 1) + '组'}}</view>
                          <view class="d-you" @click="zanzhu_shanchu(index)">-删除</view>
                        </view>
                        <view class="d-clear"></view>

                        <uv-input placeholder="获的赞助金" class="d-shang-10"  border="surround" v-model="item.name" >
                            <template v-slot:prefix>
                            	<uv-text
                            		text="获的赞助金"
                            		margin="0 10px 0 0"
                            		type="tips"
                            	></uv-text>
                            </template>
                        </uv-input>
                        <uv-input placeholder="支付赞助金" class="d-shang-10"  border="surround" v-model="item.zhifu">
                            <template v-slot:prefix>
                            	<uv-text
                            		text="支付赞助金"
                            		margin="0 10px 0 0"
                            		type="tips"
                            	></uv-text>
                            </template>
                        </uv-input>
                        <uv-input placeholder="说明" class="d-shang-10"  border="surround" v-model="item.shuoming" >
                            <template v-slot:prefix>
                              <uv-text
                                text="说明"
                                margin="0 10px 0 0"
                                type="tips"
                              ></uv-text>
                            </template>
                        </uv-input>
                      </view>
                    </view>
                  </view>
                  <view class="d-clear"></view>


                </view>
              </view>
              
			    		<uv-radio-group v-if="zanzhu_data_list_cuozuo==1" class="d-shang-10" v-model="zanzhu_data_add.zhuangtai" placement="row">
			    			<uv-radio name="2" label="关闭" class="d-you-10"></uv-radio>
			    			<uv-radio name="1" label="显示" class="d-you-10"></uv-radio>
			    			
			    		</uv-radio-group>
			    	  <uv-button v-if="zanzhu_data_list_cuozuo==0" class="d-shang-10 d-you-10" type="primary" text="添加赞助金" @click="postzanzhu_add_api" ></uv-button>
			    		<uv-button v-if="zanzhu_data_list_cuozuo==1" class="d-shang-10" type="primary" text="修改" @click="postzanzhu_data_xiugai_api"></uv-button>
			    	</view>
			    </view>

		</uv-overlay>
    

	</view>
</template>

<script>
import Api from '@/utils/api.js'; //postzanzhu_data_add_api
import ZanzhuApi from '@/utils/zanzhu_api.js';
import { getRequest,postRequest } from '@/utils/wxRequest.js';
export default {
  props: {
    // 接收显示状态属性
    zanzhu_data_show: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    cid: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      // 初始化wwwData对象，提供默认值
      wwwData: {
        www: '加载中...'
      },
      zanzhu_data_add:{
        zz_id:'',
        title:'',
        zhuangtai:2,
        id:'',
        // 初始化赞助金数组，确保模板中的v-model绑定不会出错
        zanzhu: [
          {
            name: '',
            zhifu: '',
            shuoming: ''
          }
        ]
      },
      zanzhu_data_list_cuozuo:0,
    }
  },
  created() {
    // 直接调用组件自身的$getWwwData方法
    this.getWwwDatas();
  },
  watch: {
    // 监听组件显示状态变化，当显示时触发检测接口
    'zanzhu_data_show': function(newVal) {
      if (newVal) {
        this.zanzhu_cunzai_api();
      }
    }
  },
  methods: {
    // 定义一个方法，用于获取www数据
    async getWwwDatas() {
      try {
        const res = await this.$getWwwData();
        //console.log('获取到的www数据:', res);
        // 处理获取到的www数据，例如更新组件的状态
        this.wwwData = res;
      } catch (error) {
        // console.error('获取www数据失败:', error);
      }
    },
    
    // 关闭弹窗方法，通知父组件更新显示状态
    zanzhu_data_add_close() {
      //console.log('点击');
      this.$emit('zanzhu_data_add_close', false);
    },
    
    confirm(date) {
      
    },
    
    // 添加赞助金组
    zanzhu_tianjia() {
      // 添加一个新的赞助金组对象到数组中
      this.zanzhu_data_add.zanzhu.push({
        name: '',
        zhifu: '',
        shuoming: ''
      });
      
      // 滚动到底部，确保新增的组可见
      this.$nextTick(() => {
        const scrollView = document.getElementById('d-gundong');
        if (scrollView) {
          scrollView.scrollTop = scrollView.scrollHeight;
        }
      });
    },
    
    // 删除赞助金组
    zanzhu_shanchu(index) {
      // 确保至少保留一组
      if (this.zanzhu_data_add.zanzhu.length > 1) {
        // 从数组中删除指定索引的赞助金组
        this.zanzhu_data_add.zanzhu.splice(index, 1);
      } else {
        // 如果只有一组，可以清空该组的数据但不删除
        this.zanzhu_data_add.zanzhu[0] = {
          name: '',
          zhifu: '',
          shuoming: ''
        };
        // 可以添加提示信息，告知用户至少需要保留一组
      }
    },
    //添加赞助金接口
    async postzanzhu_add_api() {
      let uid = this.$store.state.memberuid;
      let code = this.$store.state.keycode;
      let url = ZanzhuApi.postZanzhu_data_add_api(uid,code);
      
      // 非空检测
      if(!this.zanzhu_data_add.title) {
        uni.showToast({
          title: '标题不能为空',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 检测赞助金详情数组是否有数据
      if(this.zanzhu_data_add.zanzhu.length === 0) {
        uni.showToast({
          title: '请添加至少一组赞助金数据',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 检测每组赞助金数据的必要字段是否为空
      for(let i = 0; i < this.zanzhu_data_add.zanzhu.length; i++) {
        const item = this.zanzhu_data_add.zanzhu[i];
        if(!item.name) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金名称不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if(!item.zhifu) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金金额不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if(!item.shuoming) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金说明不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }
      
      // 创建指定格式的对象
      let zanzhuFormatObj = {};
      this.zanzhu_data_add.zanzhu.forEach((item, index) => {
        // 使用索引+1作为外层对象的键
        zanzhuFormatObj[index + 1] = {
          1: item.name || '', // name 对应键1
          2: item.zhifu || '', // zhifu 对应键2
          3: item.shuoming || '' // shuoming 对应键3
        };
      });
      
      // 将对象转换为JSON字符串
      let zanzhuJson = JSON.stringify(zanzhuFormatObj);
      var id_data = '&data[quanid]='+this.cid+'&data[tieid]='+this.id;
      // 构建请求数据
      var datas = "is_ajax=1&data[title]="+encodeURIComponent(this.zanzhu_data_add.title)+"&catid=1&data[zanzhuguige]="+encodeURIComponent(zanzhuJson)+id_data;
      
      let res = await postRequest(url,datas);
      if(res.data.code==1){
        uni.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000
        });
        this.zanzhu_data_add_close();
      } else {
        uni.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        });
      }
    },
    //打开组件触发检测接口
    async zanzhu_cunzai_api() {
      let uid = this.$store.state.memberuid;
      let code = this.$store.state.keycode;
      let url = ZanzhuApi.getZanzhu_cunzai_api(uid,code,this.id,this.cid);
      try {
        let res = await getRequest(url);
        if(res.data.code==1){
          // 如果有数据，直接赋值
          this.zanzhu_data_add = res.data.data;
          // 确保zanzhu数组存在
          if(!this.zanzhu_data_add.zanzhu) {
            this.zanzhu_data_add.zanzhu = [{name: '', zhifu: '', shuoming: ''}];
          }
          this.zanzhu_data_list_cuozuo = 1; 
        } else {
          // 如果没有数据，重置为初始结构而不是空对象
          this.zanzhu_data_add = {
            zz_id:'',
            title:'',
            zhuangtai:2,
            id:'',
            zanzhu: [
              {
                name: '',
                zhifu: '',
                shuoming: ''
              }
            ]
          };
        }
      } catch (error) {
        console.error('获取赞助金数据失败:', error);
        // 发生错误时也保持正确的结构
        this.zanzhu_data_add = {
          zz_id:'',
          title:'',
          zhuangtai:2,
          id:'',
          zanzhu: [
            {
              name: '',
              zhifu: '',
              shuoming: ''
            }
          ]
        };
      }
    },
    //修改赞助金
    async postzanzhu_data_xiugai_api() {
      let uid = this.$store.state.memberuid;
      let code = this.$store.state.keycode;
      let url = ZanzhuApi.postZanzhu_xiugai_api(uid,code,this.zanzhu_data_add.zz_id);
      var id_data = '&data[quanid]='+this.cid+'&data[tieid]='+this.id;
      // 赞助金数据 跟提交一样
            // 非空检测
      if(!this.zanzhu_data_add.title) {
        uni.showToast({
          title: '标题不能为空',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 检测赞助金详情数组是否有数据
      if(this.zanzhu_data_add.zanzhu.length === 0) {
        uni.showToast({
          title: '请添加至少一组赞助金数据',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 检测每组赞助金数据的必要字段是否为空
      for(let i = 0; i < this.zanzhu_data_add.zanzhu.length; i++) {
        const item = this.zanzhu_data_add.zanzhu[i];
        if(!item.name) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金名称不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if(!item.zhifu) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金金额不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if(!item.shuoming) {
          uni.showToast({
            title: '第' + (i + 1) + '组赞助金说明不能为空',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }
     
      let zanzhuFormatObj = {};
      this.zanzhu_data_add.zanzhu.forEach((item, index) => {
        // 使用索引+1作为外层对象的键
        zanzhuFormatObj[index + 1] = {
          1: item.name || '', // name 对应键1
          2: item.zhifu || '', // zhifu 对应键2
          3: item.shuoming || '' // shuoming 对应键3
        };
      });
      var zanzhuJson = JSON.stringify(zanzhuFormatObj);
      var zhuangtai_data = '&data[fstatus]='+this.zanzhu_data_add.zhuangtai;
      // 构建请求数据
      var datas = "is_ajax=1&data[id]="+this.zanzhu_data_add.zz_id+"&data[title]="+encodeURIComponent(this.zanzhu_data_add.title)+"&catid=1&data[zanzhuguige]="+encodeURIComponent(zanzhuJson)+id_data+zhuangtai_data;

      try {
        let res = await postRequest(url,datas);
        if(res.data.code==1){
          uni.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          });
          this.zanzhu_data_add_close();
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('修改赞助金数据失败:', error);
        uni.showToast({
          title: '修改赞助金数据失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
  }
}
</script>

<style>
.warp_zanzhu {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}
.rect_zanzhu {
	width: 300px;
	/*height: 300px;*/
	padding: 10px;
	background-color: #fff;
	border-radius: 10px;
}
#d-gundong {
  max-height: 200px; /* 设置最大高度，超出部分将滚动 */
  overflow-y: auto; /* 允许垂直方向滚动 */
  padding-right: 5px; /* 为滚动条留出空间 */
}

/* 自定义滚动条样式（可选） */
#d-gundong::-webkit-scrollbar {
  width: 6px;
}

#d-gundong::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

#d-gundong::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

#d-gundong::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>